<template>
  <a-card :bordered="false">
    <a-row style="border: 1px solid #d9d9d9">
      <a-col :span="3">
        <a-tree
          ref="treeBox"
          :tree-data="sortData"
          :props="defaultProps"
          style="background-color: #fff"
          :selected-keys="selectedValues"
          :defaultSelectedKeys="defaultSelectedKeys"
          @select="treeSelect"
        />
      </a-col>
      <a-col :span="21" style="border-left: 1px solid #d9d9d9">
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="12" style="margin-top: 10px;margin-left:10px">
              <a-col :span="6" v-if="!tenantId ||(tenantId && isShowShop)">
                <a-form-item :label="$t('门店')">
                  <a-select v-model="queryParam.shopCode" style="width:100%" @change="changeShop">
                    <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                      >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('商品信息')">
                  <a-input :placeholder="$t('请输入商品编码/名称/条码')" v-model="queryParam.goodsInfo" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('商品分类')">
                  <a-tree-select
                    allowClear
                    v-model="queryParam.parentKindId"
                    style="width:100%"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="treeData"
                    :search-placeholder="$t('请选择')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('库存数量')">
                  <a-select v-model="queryParam.stockQuery" style="width: 120px">
                    <a-select-option value=">">{{ $t('大于') }}</a-select-option>
                    <a-select-option value=">=">{{ $t('大于等于') }}</a-select-option>
                    <a-select-option value="=">{{ $t('等于') }}</a-select-option>
                    <a-select-option value="<=">{{ $t('小于等于') }}</a-select-option>
                    <a-select-option value="<">{{ $t('小于') }}</a-select-option>
                  </a-select>
                  <a-input-number v-model="queryParam.stock" style="width: 80px" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="12" style="margin-left:10px">
              <a-col :span="24">
                <a-form-item :labelCol="{ span: 0 }" :wrapperCol="{ span: 24 }">
                  <a-checkbox v-model="queryParam.stockZero">{{ $t('不显示0库存商品') }}</a-checkbox>
                  <a-button type="primary" @click="getList(1)" icon="search">{{ $t('查询') }}</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('重置') }}</a-button>
                  <a-button
                    type="primary"
                    icon="download"
                    @click="handleExportXls($t('库存查看'))"
                    style="margin-left: 8px"
                    v-has="'BisGoodsStockController:export'"
                    >{{ $t('导出') }}</a-button
                  >
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="table-operator" style="padding-left: 10px">
          <a-button type="primary" v-for="(func, i) in goodsFunc" :key="i" @click="handleGoodsOpt(func)" v-has="'BisGoodsStockController:handle'">
            {{ func.name }}
          </a-button>
          <a-popconfirm placement="topRight" :visible="visible" @cancel="visible = false"
            :title="$t('您确定要删除已选择的商品吗？')" 
            @confirm="() => batchDelete()">
            <a-button type="primary" v-has="'BisGoodsStockController:deleteBatch'" @click="handleClick" v-show="showCheckbox">{{ $t('批量删除') }}</a-button>
          </a-popconfirm>        
          <a-checkbox :checked="shopAllStock.ivalue == 1" @change="changeState" style="margin-left:8px;" v-if="!tenantId">{{$t('分店允许查看所有库存')}}</a-checkbox>
          <a-button type="primary" v-has="'InventoryCheck:clear'" @click="handleClear">{{ $t('一键清除') }}</a-button>
        </div>
        <a-row>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i>
            <i18n path="selected-items" tag="span">
              <a place="items" style="font-weight: 600">{{ selectedRowKeys.length }}</a>
            </i18n>
            <a style="margin-left: 24px" @click="onClearSelected">{{ $t('清空') }}</a>
          </div>
          <a-table
            size="middle"
            bordered
            class="j-table-force-nowrap"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :pagination="ipagination"
            :scroll="{x: true}"
            :row-selection="rowSelectionConfig"
            @change="handleTableChange"
          >
            <template slot="imgSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
              <a-popover v-else trigger="hover">
                <template slot="content">
                  <img :src="getImgView(text)" width="240px" />
                </template>
                <img
                  :src="getImgView(text)"
                  height="25px"
                  alt=""
                  style="max-width: 80px; font-size: 12px; font-style: italic"
                />
              </a-popover>
            </template>

            <span slot="cost" slot-scope="text">
              <span>{{ isPriceDecimal ? text.toFixed(4) : text.toFixed(0) }}</span>
            </span>
            <span slot="amount" slot-scope="text">
              <span>{{ isPriceDecimal ? text.toFixed(4) : text.toFixed(0) }}</span>
            </span>
            <span slot="action" slot-scope="text, record">
              <a v-if="record.stock == 0 && record.id" @click="handleDelete(record.id)" v-has="'BisGoodsStockController:handle'">{{ $t('删除') }}</a>
            </span>
            <span slot="stock" slot-scope="text, record">
              <a @click="onChange(record)">{{ record.stock.toFixed(0) }}</a>
            </span>
            <template slot="footer">
              <div style="font-weight: bold">
                <span style="margin-left: 15px; margin-right: 5px">{{ $t('总数量') }}：</span>
                <span>{{ totalNum }}</span>
                <span style="margin-left: 15px; margin-right: 5px">{{ $t('总金额') }}：</span>
                <span>{{ isPriceDecimal ? totalAmount.toFixed(4): totalAmount.toFixed(0) }}</span>
              </div>
            </template>
          </a-table>
        </a-row>
      </a-col>
    </a-row>
    <inventory-detail-modal ref="modalForm" />
    <goods-instock-standby-modal ref="instockForm" @ok="getList(1)" />
    <in-store-standby-modal ref="inForm" @ok="getList(1)" />
    <out-store-standby-modal ref="outForm" @ok="getList(1)" />
    <sales-allot-standby-modal ref="allotForm" @ok="getList(1)" />
    <return-goods-standby-modal ref="returnForm" @ok="getList(1)" />
    <goods-inventory-standby-modal ref="inventoryForm" @ok="getList(1)" />
    <goods-stock-clear-modal ref="clearForm" @ok="getList(1)" />
  </a-card>
</template>
<script>
import Vue from 'vue'
import { TENANT_ID } from '@/store/mutation-types'
import { httpAction, getAction, deleteAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import InventoryDetailModal from './modules/InventoryDetailModal'
import GoodsInstockStandbyModal from './modules/GoodsInstockStandbyModal'
import InStoreStandbyModal from './modules/InStoreStandbyModal'
import OutStoreStandbyModal from './modules/OutStoreStandbyModal'
import SalesAllotStandbyModal from './modules/SalesAllotStandbyModal'
import ReturnGoodsStandbyModal from './modules/ReturnGoodsStandbyModal'
import GoodsInventoryStandbyModal from './modules/GoodsInventoryStandbyModal'
import GoodsStockClearModal from './modules/GoodsStockClearModal'

export default {
  name: 'InventoryCheck',
  components: {
    InventoryDetailModal,
    GoodsInstockStandbyModal,
    InStoreStandbyModal,
    OutStoreStandbyModal,
    SalesAllotStandbyModal,
    ReturnGoodsStandbyModal,
    GoodsInventoryStandbyModal,
    GoodsStockClearModal
  },
  data() {
    return {
      description: this.$t('库存查看'),
      isPriceDecimal: true,
      treeData: [],
      defaultSelectedKeys: [],
      selectedValues: [],
      loading: false,
      columns: [
        {
          title: this.$t('商品编码'),
          align: 'center',
          dataIndex: 'goodsCode',
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'goodsId_dictText',
        },
        {
          title: this.$t('分类'),
          align: 'center',
          dataIndex: 'kindName',
        },
        {
          title: this.$t('库存数量'),
          align: 'center',
          dataIndex: 'stock',
          scopedSlots: { customRender: 'stock' },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('平均成本'),
          align: 'center',
          dataIndex: 'cost',
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'cost' },
        },
        {
          title: this.$t('总金额'),
          align: 'center',
          dataIndex: 'amount',
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'amount' },
        },
        {
          title: this.$t('条形码'),
          align: 'center',
          dataIndex: 'barCode',
        },
        {
          title: this.$t('单位'),
          align: 'center',
          dataIndex: 'unit_dictText',
        },
        {
          title: this.$t('规格'),
          align: 'center',
          dataIndex: 'standard',
        },
        {
          title: this.$t('供应商'),
          align: 'center',
          dataIndex: 'supplierId_dictText',
        },
        {
          title: this.$t('售价'),
          align: 'center',
          dataIndex: 'price',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(2);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('商品图片'),
          align: 'center',
          dataIndex: 'picture',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: this.$t('最后更新时间'),
          align: 'center',
          dataIndex: 'updateTime',
        },
        {
          title: this.$t('操作'),
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      queryParam: {
        goodsInfo: '',
        parentKindId: '',
        stockQuery: '>',
        stock: null,
        stockZero: false,
        shopCode: this.tenantId===0?0:""
      },
      sortList: [],
      sortData: [],
      selectedRowKeys: [],
      selectionRows: [],
      batchList: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      defaultSelectedKeys: [],
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      url: {
        list: 'goods/bisGoodsStock/total',
        delete: '/goods/bisGoodsStock/delete',
        exportXlsUrl: '/goods/bisGoodsStock/exportXls',
      },
      totalNum: 0,
      totalAmount: 0,
      tenantId: Vue.ls.get(TENANT_ID) ? Vue.ls.get(TENANT_ID) : 0,
      goodsFunc: JSON.parse(localStorage.getItem('goodsFunc')),
      shops: [],
      shopAllStock: {
        name: 'shopAllStock',
        ivalue: 0,
        comment: '分店允许查看所有库存',
      },
      isShowShop: 0,
      showCheckbox: false,
      visible: false
    }
  },
  async created() {
    await this.getAllStock()
    initDictOptions('bis_shop,name,code').then((res) => {
      if (res.success) {
        this.shops = res.result
        this.shops.unshift({ value: 0, title: this.$t('总部') })
        this.shops.unshift({ value: '', title: this.$t('全部') })
      }
    })
    this.isPriceDecimal = await this.getRule()
    this.getSortList()
    this.select()
    this.initDictConfig()
  },
  computed:{
    rowSelectionConfig() {
      return this.showCheckbox
        ? {
            type: 'checkbox', // 复选框类型
            selectedRowKeys: this.selectedRowKeys, // 选中的行
            onChange: this.onSelectChange, // 选中变化时的回调
          }
        : null; // 不显示复选框列
    },
  },
  methods: {
    handleClick(){
      if(this.selectedRowKeys.length>0){
        this.visible = true;
      }else{
        this.$message.warning(this.$t('请选择要删除的商品'))
      }
    },
    handleClear(){
      this.$refs.clearForm.edit()
    },
    initDictConfig() {
      if (localStorage.getItem('operateCoin') == 1) {
        this.columns.splice(this.columns.length - 3, 0, {
          title:this.$t('币兑换值'),
          align:"center",
          dataIndex: 'coin',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(2);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        })
      }
      if (localStorage.getItem('operateLottery') == 1) {
        this.columns.splice(this.columns.length - 3, 0, {
          title:this.$t('彩票兑换值'),
          align:"center",
          dataIndex: 'lottery',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(0);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        })
      }
      if (localStorage.getItem('operateCredit') == 1) {
        this.columns.splice(this.columns.length - 3, 0, {
          title:this.$t('积分兑换值'),
          align:"center",
          dataIndex: 'integral',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(0);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        })
      }
      if (localStorage.getItem('operateALottery') == 1) {
        this.columns.splice(this.columns.length - 3, 0, {
          title:this.$t('A票兑换值'),
          align:"center",
          dataIndex: 'alottery',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(0);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        })
      }
      if (localStorage.getItem('operateACoin') == 1) {
        this.columns.splice(this.columns.length - 3, 0, {
          title:this.$t('A币兑换值'),
          align:"center",
          dataIndex: 'zlottery',
          customRender: (text, r) => {
            if(!text){
              text = 0
            }
            return text.toFixed(0);
          },
          customCell: function (text, record) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        })
      }
      this.queryByName()
    },
    getAllStock(){
      return new Promise(resolve=>{
        getAction('/goods/bisGoodsStock/shopAllStock').then(res=>{
          if(res.success){
            this.isShowShop = res.result
          }else{
            this.isShowShop = 0
          }
          resolve()
        })
      })
    },
    queryByName() {
      getAction('/bis/bisSysParameter/queryByName', { name: 'shopAllStock' }).then(res=>{
        if(res.success){
          this.shopAllStock = Object.assign({}, res.result)
        }else{
          this.shopAllStock = {
            name: 'shopAllStock',
            ivalue: 0,
            comment: '分店允许查看所有库存',
          }
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    handleGoodsOpt(func) {
      let obj = {}
      if(this.queryParam.storeId){
        obj.storeId = this.queryParam.storeId
      }
      if(this.selectionRows.length > 0){
        obj.selectedIds = this.selectionRows.map(s=>{return s.goodsId})
      }
      if (func.path.indexOf('GoodsInstockList') > -1) {
        this.$refs.instockForm.add(obj)
        this.$refs.instockForm.title = this.$t('新增采购单')
        this.$refs.instockForm.disableSubmit = false
      }
      if (func.path.indexOf('OtherInOfStore') > -1) {
        this.$refs.inForm.add(obj)
        this.$refs.inForm.title = this.$t('新增入库单')
        this.$refs.inForm.disableSubmit = false
      }
      if (func.path.indexOf('OtherOutOfStore') > -1) {
        this.$refs.outForm.add(obj)
        this.$refs.outForm.title = this.$t('新增出库单')
        this.$refs.outForm.disableSubmit = false
      }
      if (func.path.indexOf('SalesAllotList') > -1) {
        this.$refs.allotForm.add(obj)
        this.$refs.allotForm.title = this.$t('新增调拨单')
        this.$refs.allotForm.disableSubmit = false
      }
      if (func.path.indexOf('ReturnGoodsList') > -1) {
        this.$refs.returnForm.add(obj)
        this.$refs.returnForm.title = this.$t('新增返货单')
        this.$refs.returnForm.disableSubmit = false
      }
      if (func.path.indexOf('GoodsInventoryList') > -1) {
        this.$refs.inventoryForm.add(obj)
        this.$refs.inventoryForm.title = this.$t('新增盘点单')
        this.$refs.inventoryForm.disableSubmit = false
      }
    },
    getRule() {
      return new Promise((resolve) => {
        getAction('/bis/bisSysParameter/list', { name: 'isPriceDecimal' }).then((res) => {
          let value = true
          if (res.success && res.result.total > 0) {
            let isPriceDecimal = res.result.records[0]
            value = isPriceDecimal.ivalue ? true : false
          }
          resolve(value)
        })
      })
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    treeSelect(data, { node, event }) {
      this.onClearSelected()
      if (data.length === 0) {
        return;
      }
      this.selectedValues = data;
      this.queryParam.storeId = data[0];
      const dataRef = node.dataRef;
      if(data[0] == '' || dataRef.hasChild === '1'){
        this.showCheckbox = false
      }else{
        this.showCheckbox = true
      }
      this.getList(1)
    },
    getSortList(item) {
      let that = this
      that.rootItem = item
      that.sortList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      if(that.tenantId){
        param.tenantId = that.tenantId
      }else{
        param.shopCode = that.queryParam.shopCode
      }
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          that.sortList = res.result.records
          if (that.sortList.length > 0) {
            that.sortList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.sortData = that.getDataByResult(that.sortList)
            that.sortData.unshift({ key: '', id: '', title: that.$t('全部') })
            that.defaultSelectedKeys.push(that.sortData[0].key);
            that.selectedValues = [...that.defaultSelectedKeys];
            that.getList(1)
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      if(that.tenantId){
        query.tenantId = that.tenantId
      }else{
        query.shopCode = that.queryParam.shopCode
      }
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.sortData = [...that.sortData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getList(num) {
      let that = this
      that.loading = true
      let querydata = {}
      let querydatas = {}
      querydata.pageNo = 1
      querydata.pageSize = that.ipagination.pageSize
      querydata.goodsInfo = that.queryParam.goodsInfo
      querydata.parentKindId = that.queryParam.parentKindId
      querydata.storeId = that.queryParam.storeId
      querydata.stockQuery = that.queryParam.stockQuery
      querydata.stock = that.queryParam.stock
      if (that.queryParam.stockZero == true) {
        querydata.isZeroStock = false
      }
      if(that.tenantId){
        querydata.tenantId = that.tenantId
      }else{
        querydata.shopCode = that.queryParam.shopCode
      }
      if(that.isShowShop == 1){
        querydata.shopCode = that.queryParam.shopCode
      }
      getAction(that.url.list, querydata).then((res) => {
        if (res.success) {
          that.totalNum = 0
          that.totalAmount = 0
          if (res.result.records && res.result.records.length > 0) {
            that.totalNum = res.result.records[0].stock
            that.totalAmount = res.result.records[0].amount
          }
        }else{
          that.$message.error(res.message)
        }
      })
      querydatas = Object.assign({}, querydata)
      querydatas.groupBy = 'goods_id'
      querydatas.pageNo = num
      getAction(that.url.list, querydatas)
        .then((res) => {
          if (res.success) {
            that.dataSource = res.result.records
            if (res.result.total) {
              that.ipagination.total = res.result.total
            } else {
              that.ipagination.total = 0
            }
            that.ipagination.current = res.result.current
            that.defaultSelectedKeys.push(that.sortData[0].key)
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      if(that.tenantId){
        param.tenantId = that.tenantId
      }else{
        param.tenantId = that.queryParam.shopCode
      }
      getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.treeData = that.getDataByResult(res.result.records)
            that.treeData.unshift({ key: '', id: '', value: '', title: that.$t('全部') })
          } else {
            that.treeData = []
          }
        } else {
          that.$alert(res.message, that.$t('提示'), {
            confirmButtonText: that.$t('确定'),
            callback: (action) => {},
          })
        }
      })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      if(that.tenantId){
        query.tenantId = that.tenantId
      }else{
        query.tenantId = that.queryParam.shopCode
      }
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
            that.$forceUpdate()
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let param = {}
      param.goodsInfo = this.queryParam.goodsInfo
      param.parentKindId = this.queryParam.parentKindId
      if(this.tenantId){
        param.tenantId = this.tenantId
      }else{
        param.shopCode = this.queryParam.shopCode
      }
      param.storeId = this.queryParam.storeId
      param.stockQuery = this.queryParam.stockQuery
      param.stock = this.queryParam.stock
      if (this.queryParam.stockZero == true) {
        param.isZeroStock = false
      }
      param.groupBy = 'goods_id'
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    searchReset() {
      this.showCheckbox = false
      this.queryParam = {
        goodsInfo: '',
        parentKindId: '',
        stockQuery: '>',
        stock: null,
        stockZero: false,
        shopCode: this.tenantId===0?0:""
      }
      this.selectedValues = [...this.defaultSelectedKeys];
      this.$forceUpdate()
      this.queryParam.storeId = this.selectedValues[0];
      this.getList(1)
    },
    onChange(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = this.$t('库存明细')
    },
    batchDelete() {
      let that = this
      const ids = that.selectedRowKeys.join(',')
      deleteAction('/goods/bisGoodsStock/deleteBatch', { ids: ids }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getList(1)
        } else {
          that.$message.warning(res.message)
        }
        that.visible = false
        that.onClearSelected()
      })
    },
    handleDelete(id) {
      let that = this
      if (!that.url.delete) {
        that.$message.error(that.$t('请设置url.delete属性'))
        return
      }
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getList(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    reCalculatePage(count) {
      //总数量-count
      let total = this.ipagination.total - count
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize)
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex
      }
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      this.ipagination = pagination
      this.getList(pagination.current)
    },
    changeShop(){
      this.getSortList()
      this.select()
    },
    changeState(e){
      this.$set(this.shopAllStock, 'ivalue', e.target.checked ? 1 : 0)
      let url = '',
        method = ''
      if (this.shopAllStock.id) {
        url = '/bis/bisSysParameter/edit'
        method = 'put'
      }else{
        url = '/bis/bisSysParameter/add'
        method = 'post'
      }
      httpAction(url, this.shopAllStock, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryByName()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    hasChildrenBFS(arr, targetId) {
      const queue = [...arr];
      while (queue.length > 0) {
        const item = queue.shift();
        if (item.id === targetId) {
          return item.children && item.children.length > 0;
        }
        if (item.children) {
          queue.push(...item.children);
        }
      }
      return false;
    },
  },
}
</script>
<style scoped>
.col-sort {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
}
.col-sort-selected {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
  background-color: #f0f7ff;
}
</style>